"""初始化系统菜单"""
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from sqlalchemy import inspect, text
from sqlalchemy.orm import Session
from database.db import engine, Base, get_db
from models.menu import Menu
from models.user import Permission

def init_menus(db: Session):
    """初始化系统菜单"""
    
    # 先创建menus表（如果不存在）
    if not inspect(engine).has_table('menus'):
        Base.metadata.create_all(bind=engine, tables=[Menu.__table__])
        print("已创建menus表")
    
    # 先检查menu_permissions关联表是否存在
    if not inspect(engine).has_table('menu_permissions'):
        from models.menu import menu_permissions
        menu_permissions.create(engine)
        print("已创建menu_permissions关联表")
    
    # 定义预定义菜单
    predefined_menus = [
        {
            "name": "仪表盘",
            "path": "",
            "component": "views/Dashboard.vue",
            "icon": "i-home",
            "parent_id": None,
            "sort_order": 1,
            "is_visible": True,
            "permission_names": []  # 不需要权限
        },
        {
            "name": "无人机管理",
            "path": "drones",
            "component": "views/Drones.vue",
            "icon": "i-plane",
            "parent_id": None,
            "sort_order": 2,
            "is_visible": True,
            "permission_names": ["drone_manage"]
        },
        {
            "name": "无人机类型管理",
            "path": "drone-types",
            "component": "views/DroneTypes.vue",
            "icon": "i-box",
            "parent_id": None,
            "sort_order": 3,
            "is_visible": True,
            "permission_names": ["drone_manage"]
        },
        {
            "name": "航线管理",
            "path": "routes",
            "component": "views/Routes.vue",
            "icon": "i-map",
            "parent_id": None,
            "sort_order": 4,
            "is_visible": True,
            "permission_names": ["route_manage"]
        },
        {
            "name": "用户管理",
            "path": "users",
            "component": "views/Users.vue",
            "icon": "i-user",
            "parent_id": None,
            "sort_order": 10,
            "is_visible": True,
            "permission_names": ["user_manage"]
        },
        {
            "name": "角色管理",
            "path": "roles",
            "component": "views/Roles.vue",
            "icon": "i-s-grid",
            "parent_id": None,
            "sort_order": 11,
            "is_visible": True,
            "permission_names": ["role_manage"]
        },
        {
            "name": "菜单管理",
            "path": "menus",
            "component": "views/Menus.vue",
            "icon": "i-menu",
            "parent_id": None,
            "sort_order": 12,
            "is_visible": True,
            "permission_names": ["system_config"]
        },
        {
            "name": "数据字典管理",
            "path": "dicts",
            "component": "views/Dict.vue",
            "icon": "i-list",
            "parent_id": None,
            "sort_order": 13,
            "is_visible": True,
            "permission_names": ["system_config"]
        },
        {
            "name": "部门管理",
            "path": "departments",
            "component": "views/Departments.vue",
            "icon": "i-briefcase",
            "parent_id": None,
            "sort_order": 14,
            "is_visible": True,
            "permission_names": ["department_manage"]
        }
    ]
    
    # 先获取所有权限
    all_permissions = db.query(Permission).all()
    permission_dict = {perm.name: perm for perm in all_permissions}
    
    # 创建或更新菜单
    for menu_data in predefined_menus:
        # 查找现有菜单
        existing_menu = db.query(Menu).filter(Menu.name == menu_data["name"]).first()
        
        if existing_menu:
            # 更新现有菜单
            existing_menu.path = menu_data["path"]
            existing_menu.component = menu_data["component"]
            existing_menu.icon = menu_data["icon"]
            existing_menu.parent_id = menu_data["parent_id"]
            existing_menu.sort_order = menu_data["sort_order"]
            existing_menu.is_visible = menu_data["is_visible"]
            
            # 更新权限关联
            menu_permissions = []
            for perm_name in menu_data["permission_names"]:
                if perm_name in permission_dict:
                    menu_permissions.append(permission_dict[perm_name])
            existing_menu.permissions = menu_permissions
            
            db.commit()
            print(f"已更新菜单: {menu_data['name']}")
        else:
            # 创建新菜单
            new_menu = Menu(
                name=menu_data["name"],
                path=menu_data["path"],
                component=menu_data["component"],
                icon=menu_data["icon"],
                parent_id=menu_data["parent_id"],
                sort_order=menu_data["sort_order"],
                is_visible=menu_data["is_visible"]
            )
            
            # 关联权限
            menu_permissions = []
            for perm_name in menu_data["permission_names"]:
                if perm_name in permission_dict:
                    menu_permissions.append(permission_dict[perm_name])
            new_menu.permissions = menu_permissions
            
            db.add(new_menu)
            db.commit()
            db.refresh(new_menu)
            print(f"已创建菜单: {menu_data['name']}")
    
if __name__ == "__main__":
    print("开始初始化系统菜单...")
    
    # 获取数据库会话
    db = next(get_db())
    try:
        init_menus(db)
        print("菜单初始化完成！")
    except Exception as e:
        db.rollback()
        print(f"菜单初始化失败: {str(e)}")
        raise
    finally:
        db.close()